package com.zimi.common.service;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.zimi.bean.Column;
import com.zimi.common.mapper.CustomMapper;
import com.zimi.common.model.ColumnInfo;
import com.zimi.util.DbUtil;
import com.zimi.util.DynamicBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.support.JdbcUtils;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.*;

@Service
public class CustomService {


    @Autowired
    private CustomMapper customMapper;

    @Autowired
    private DataSource dataSource;

    private String dataName = "erp_jyx";
    private String regColumn = "[^\\u4E00-\\u9FA5A-Za-z1-9].*";

    /**
     * 获取所有表名及其注释
     */
    public Map<String, String> tables() {
        List<ColumnInfo> list = customMapper.getTables(dataName);
        Map<String, String> map = new LinkedHashMap<>();
        list.stream().filter(Objects::nonNull)
                .forEach(item -> {
                    String iN = StringUtils.underlineToCamel(item.getName());
                    String iC = item.getComment().replaceAll("[a-z]", "").trim().length() > 0 ? item.getComment().trim().replaceAll("[^\\u4E00-\\u9FA5A-Z].*", "") : iN;
                    map.put(iN, iC);
                });
        return map;
    }

    /**
     * 获取列名及注释1
     *
     * @param name 实体名
     * @return {comment= name}:Map
     */
    public Map<String, String> queryMap(String name) {
        List<ColumnInfo> list = customMapper.getCols(StringUtils.camelToUnderline(name), dataName);
        Map<String, String> map = new LinkedHashMap<>();
        list.stream().filter(Objects::nonNull)
                .forEach((item) -> {
                    boolean flag = item.getComment().replaceAll("[a-z]", "").trim().length() > 0;
                    String iN = StringUtils.underlineToCamel(item.getName());
                    String iC = flag ? item.getComment().trim().replaceAll(regColumn, "") : iN;
                    map.put(iC, iN);
                });
        return map;
    }

    /**
     * 获取列名及注释2
     *
     * @param name 实体名
     * @return {name=comment}:Map
     */
    public Map<String, String> cols(String name) {
        List<ColumnInfo> list = customMapper.getCols(StringUtils.camelToUnderline(name), dataName);
        Map<String, String> map = new LinkedHashMap<>();
        list.forEach(item -> {
                    String iN = StringUtils.underlineToCamel(item.getName());
                    String iC = item.getComment().replaceAll(regColumn, "").trim().length() > 0 ? item.getComment().trim().replaceAll("[^\\u4E00-\\u9FA5A-Z].*", "") : iN;
                    map.put(iN, iC);
                });
        return map;
    }

    /**
     * 添加索引
     *
     * @param tableName 表名
     * @param indexName 索引名
     * @param ins       索引列
     * @return boolean
     */
    public boolean addIns(String tableName, String indexName, String ins) {
        try {
            customMapper.addIns(tableName, indexName, ins);
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    /**
     * 移除索引
     *
     * @param tableName 表名
     * @param indexName 索引名
     * @return boolean
     */
    public boolean dropIns(String tableName, String indexName) {
        try {
            customMapper.dropIns(tableName, indexName);
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    public int getIns(String tableName, String indexName) {
        return customMapper.getIns(tableName, dataName, indexName);
    }


    public Map<String, String> getColumn(String tableName) {
        Map<String, String> map = new HashMap<String, String>();
        try {
            Connection connDb = this.dataSource.getConnection();
            List<Column> list = DbUtil.getTableColumns(connDb, connDb.getCatalog(), null, tableName);

            if (list.size() > 0) {
                for (Column field : list) {
                    String[] tempName = (field.getName()).split("_");
                    StringBuilder conName = new StringBuilder();
                    for (int k = 0; k < tempName.length; k++) {
                        if (k == 0) {
                            conName = new StringBuilder(tempName[0]);
                        } else {
                            conName.append(tempName[k].substring(0, 1).toUpperCase()).append(tempName[k].substring(1));
                        }
                    }

                    map.put(conName.toString(), field.getRemark());
                }
                return map;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return map;
    }

    public Object toDynamicObject(ResultSet rs, int rowNum) throws SQLException {
        DynamicBean dyBean = null;
        ResultSetMetaData rsmd = rs.getMetaData();
        if (rsmd != null) {
            int columnCount = rsmd.getColumnCount();
            HashMap<String, Class<Object>> propertyMap = new HashMap<>();
            for (int index = 1; index <= columnCount; index++) {//JdbcUtils自己查spring API
                String column = JdbcUtils.lookupColumnName(rsmd, index);
                String propertyName = JdbcUtils.convertUnderscoreNameToPropertyName(column);
                propertyMap.put(propertyName, Object.class);//添加动态属性 此时person_address ==>personAddress
            }
            dyBean = new DynamicBean(propertyMap);
            for (int index = 1; index <= columnCount; index++) {
                String column = JdbcUtils.lookupColumnName(rsmd, index);
                String propertyName = JdbcUtils.convertUnderscoreNameToPropertyName(column);
                Object value = JdbcUtils.getResultSetValue(rs, index);
                dyBean.setValue(propertyName, value);//设置值
            }
        }
        assert dyBean != null;
        return dyBean.getObject();
    }

}
